<?php

/**
 * @Author: Wang Chunsheng 2192138785@qq.com
 * @Date:   2020-03-08 03:04:55
 * @Last Modified by:   Wang Chunsheng 2192138785@qq.com
 * @Last Modified time: 2020-03-14 02:04:26
 */

namespace api\modules\wechat;

use Yii;

/**
 * wechat module definition class
 */
class module extends \yii\base\Module
{
    /**
     * {@inheritdoc}
     */
    public $controllerNamespace = 'api\modules\wechat\controllers';

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        parent::init();
        /* 加载语言包 */
        if (!isset(Yii::$app->i18n->translations['wechat'])) {
            Yii::$app->i18n->translations['wechat'] = [
                'class' => 'yii\i18n\PhpMessageSource',
                'sourceLanguage' => 'en',
                'basePath' => '@api/modules/wechat/messages',
            ];
        }
        $config = require(__DIR__ . '/config.php');
        // 获取应用程序的组件
        $components = \Yii::$app->getComponents();

        // 遍历子模块独立配置的组件部分，并继承应用程序的组件配置
        foreach ($config['components'] as $k => $component) {
            if (isset($component['class']) && isset($components[$k]) == false) {
                continue;
            }
            $config['components'][$k] = array_merge($components[$k], $component);
        }
        $settings = Yii::$app->settings;
        // 支付参数设置
        $config['params']['wechatPaymentConfig'] = [
            'app_id'             => $settings->get('Wechatpay', 'app_id'),
            'mch_id'             => $settings->get('Wechatpay', 'mch_id'),
            'key'                => $settings->get('Wechatpay', 'key'),  // API 密钥
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            // 'cert_path'          => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
            // 'key_path'           => 'path/to/your/key',      // XXX: 绝对路径！！！！
            'notify_url'         =>  Yii::$app->request->hostInfo . $settings->get('Wechatpay', 'notify_url'),
        ];
        // 小程序参数设置
        $config['params']['wechatMiniProgramConfig'] = [
            'app_id'             => $settings->get('Wxapp', 'AppId'),
            'secret'             => $settings->get('Wxapp', 'AppSecret'),
        ];


        // 将新的配置设置到应用程序
        // 很多都是写 Yii::configure($this, $config)，但是并不适用子模块，必须写 Yii::$app
        \Yii::configure(\Yii::$app, $config);
    }
}
